package done;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;

import javax.imageio.ImageIO;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingWorker;



public class EnergyScale extends SwingWorker<Boolean, Boolean> implements
		ScaleWriter {

	private JPanel threadPanel;
	private BufferedImage scale;
	private double nextData = 0;
	private String nextTime = new String();
	private int nextIndex = 0;
	private LinkedList<Information> list = new LinkedList<Information>();

	public EnergyScale() {
		nextIndex=1;
		list = new LinkedList<Information>();
		try {
			scale = ImageIO.read(new File("lib/EnergyScale.png"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	protected Boolean doInBackground() throws Exception {
		Information i;	
		while ((i = list.poll()) != null ) {		
			nextData = i.getData();
			nextTime = i.getTime();
			int max =scale.getHeight();
			double save = nextData;
			nextData /= 15;
			if (nextData <= 0)
				nextData = 0;
			if (nextData >= max)
				nextData = max - 1;
			int rgb = scale.getRGB(2, (int) nextData);
			int red = (rgb & 0x00ff0000) >> 16;
			int green = (rgb & 0x0000ff00) >> 8;
			int blue = rgb & 0x000000ff;
			JLabel label = new JLabel();
			label.setToolTipText("Energy at " + nextTime + "\n  " + save
					+ " Watt");
			label.setBackground(new Color(red, green, blue));
			label.setBounds(nextIndex * 2, 0, 2, size);
			label.setOpaque(true);
			nextIndex++;
			threadPanel.add(label);
			threadPanel.setPreferredSize(new Dimension(nextIndex * 2+2, size));
			threadPanel.setSize(new Dimension(nextIndex * 2+2, size));
			threadPanel.repaint();
		}
		if(i==null && hasFinished==false){		
			while(list.size()<1 && hasFinished==false)
				{
					Thread.sleep(10);
				}
				doInBackground();
			}else 
			{
				System.out.println("done2");
				return true;
			}		
		System.out.println("done1");
		return true;
	}

	@Override
	public void writeNext(Information i) {
			list.add(i);
	}

	@Override
	public void setPanel(JPanel panel) {
		threadPanel = panel;

	}

	private boolean hasFinished = false;

	@Override
	public void finished() {
		hasFinished = true;
	}

	public void runWorker()
	{
		this.execute();
	}

}
